package com.neuedu.it.mylink.controller.interceptor;

import com.neuedu.it.mylink.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":4001,\"msg\":\"请先登录\",data:null}");
            return false;
        }
        try {
            Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
            User u = claims.get("user", User.class);
            System.out.println(u);
            request.setAttribute("user", u);
            return true;
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":4001,\"msg\":\"凭证过期或被篡改，请重新登录\",data:null}");
            return false;
        }

    }
}
